var $ = layui.$;


var clearObjIndex = {
	urlmatch:null,
	init:function(){
		console.info(chrome.tabs);
		if(chrome.tabs.getCurrent){
			chrome.tabs.query({active: true, lastFocusedWindow: true},function (tab) {
			    console.log(tab);
//				var url = tab.url;
				var url = tab[0].url;
				var yuming = getYuming(url);
				clearObjIndex.urlmatch = yuming;
				clearObjIndex.initConfig(url);
			});
			clearObjIndex.setListener();
		}else if(chrome.tabs.getSelected){
			chrome.tabs.getSelected(null, function (tab) {
			    console.log(tab);
				var url = tab.url;
				var yuming = getYuming(url);
				clearObjIndex.urlmatch = yuming;
				clearObjIndex.initConfig(url);
			});
			clearObjIndex.setListener();
		}else if(chrome.tabs.query){
			chrome.tabs.query({active: true, lastFocusedWindow: true}, 
				tabs => {
				    var url = tabs[0].url;
				    // use `url` here inside the callback because it's asynchronous!
			    }
			);
		}else{
			layui.layer.msg("无api可用");
		}
		
	},
	
	initDom:function(res){
		if(res){
			layui.form.val("formdata",res);
			if(res.switchOn){
				$("[name=switchOn]").attr("checked",true);
			}
			layui.form.render();
		}
	},
	
	initConfig:function(url){
		chrome.storage.sync.get("common_config", function(res) {
			if(res){
				var common_config = res["common_config"] || {};
				var switchOn = common_config.switchOn;
				if(switchOn){
					$("[name=switchOn]").attr("checked",true);
				}
			}
			
		});
		chrome.storage.sync.get(clearObjIndex.urlmatch, function(res) {
			res = res[clearObjIndex.urlmatch];
			$("#urlmatch").val(clearObjIndex.urlmatch);
			clearObjIndex.initDom(res);
		});
		$("#urlTxt").html(url);
	},
	getConfigFromHtml:function(){
		var formdata = layui.form.val("formdata");
		var switchOn = $("#switchOn").is(":checked"); 
		formdata.switchOn = switchOn;
		console.info(formdata);
	    return formdata;
	},
	// 导出到粘贴板
	export:function(etype){
		chrome.storage.sync.get(clearObjIndex.urlmatch, function(res) {
			var out = {etype:etype};
			if(etype == 1){ // 导出当前
				res = res[clearObjIndex.urlmatch];
				// out.url = clearObjIndex.urlmatch;
			}
			out.data = res;
			var str = JSON.stringify(out);
			clearObjIndex.copyTextToClipboard(str);
			layui.layer.msg("已导出到粘贴板");
		});
	},
	
	// 从粘贴板导入
	import:function(data){
		
		if(!data){
			layui.layer.msg("贴版没有数据");
			return;
		}
		try{
			data = JSON.parse(data);
		}catch{
			layui.layer.msg("贴版数据不正确，需要json格式。请导入【导出的数据】");
			return;
		}
		if(!data.etype){
			layui.layer.msg("贴版数据不正确,需要etype");
		}
		if(data.etype-0 == 1){ // 部分
		    var url = clearObjIndex.urlmatch;
			var flag = false;
			if(data.url){
				url = data.url;
			}
			flag = url == clearObjIndex.urlmatch? true : false;
			var targetData = data.data;
			var dataToSave = {};
			dataToSave[url] = targetData;
			chrome.storage.sync.set(dataToSave, function(res) {
				layui.layer.msg("导入成功");
				if(flag){
					clearObjIndex.initDom(targetData);
				}
			});
		}else{
			var targetData = data.data;
			// 如果导入配置中有当前的url，则把配置渲染到页面
			var currConfig = null;
			for(var key in targetData){
				if(key == clearObjIndex.urlmatch){
					currConfig = targetData[key];
					break;
				}
			}
			chrome.storage.sync.set(targetData, function(res) {
				layui.layer.msg("导入成功");
				if(currConfig)clearObjIndex.initDom(currConfig);
			});
		}
	},
	setListener:function(){
		$("#save").click(function(e){
            var obj = clearObjIndex.getConfigFromHtml();
			var objtosave = {};
			objtosave[clearObjIndex.urlmatch] = obj;
			chrome.storage.sync.set(objtosave, function(res) {
				layui.layer.msg("保存成功");
			});
		});
		$("#outportsetting1").click(function(e){ // 导出当前
		    clearObjIndex.export(1);
		});
		$("#outportsetting2").click(function(e){ // 导出全部
		    layui.layer.msg("暂不支持");
		    return;
		    clearObjIndex.export(2);
		});
		$("#importsetting").click(function(e){
			// 从张贴版获取数据
			var clipboardText = clearObjIndex.getFromClipboard();
			// copyTextToClipboard("Hi" + clipboardText); //prepends "Hi" to the clipboard text
			clearObjIndex.import(clipboardText);
		});
	},
	copyTextToClipboard:function(text) {
	  //Create a textbox field where we can insert text to. 
	  var copyFrom = document.createElement("textarea");
	
	  //Set the text content to be the text you wished to copy.
	  copyFrom.textContent = text;
	
	  //Append the textbox field into the body as a child. 
	  //"execCommand()" only works when there exists selected text, and the text is inside 
	  //document.body (meaning the text is part of a valid rendered HTML element).
	  document.body.appendChild(copyFrom);
	
	  //Select all the text!
	  copyFrom.select();
	
	  //Execute command
	  document.execCommand('copy');
	
	  //(Optional) De-select the text using blur(). 
	  copyFrom.blur();
	
	  //Remove the textbox field from the document.body, so no other JavaScript nor 
	  //other elements can get access to this.
	  document.body.removeChild(copyFrom);
	},
	getFromClipboard:function(){
		var t = document.createElement("input");
		document.body.appendChild(t);
		t.focus();
		document.execCommand("paste");
		var clipboardText = t.value; //this is your clipboard data
		document.body.removeChild(t);
		return clipboardText;
	}
}
layui.use(['jquery','form','layer'],function(){
	$ = layui.$;
	clearObjIndex.init();
});